package com.whitedust.top40;

import com.whitedust.structure.ListNode;

/**
 * @author A
 * @since 2025/11/5 10:36
 */

public class Top37 {
    public ListNode detectCycle(ListNode head) {
        ListNode slow = head;
        ListNode fast = head;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
            if (slow == fast) {
                //当快慢指针相遇时，慢指针到入口距离等于头指针到入口距离
                while (slow != head) {
                    slow = slow.next;
                    head = head.next;
                }
                return slow;
            }
        }
        return null;
    }
}
